/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>

*/
package cmd

import (
	"context"
	"encoding/base64"
	"fmt"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
	"github.com/spf13/cobra"
	"operator/cicd/util"
	util2 "operator/pkg/util"
)

// loginCmd represents the login command
var loginCmd = &cobra.Command{
	Use:   "login",
	Short: "login to docker repo",
	Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
	Run: func(cmd *cobra.Command, args []string) {
		host, err := cmd.Flags().GetString("host")
		if err != nil {
			fmt.Println(err)
			return
		}
		if host == "" {
			fmt.Println("please set host info")
			return
		}
		username, err1 := cmd.Flags().GetString("username")
		password, err2 := cmd.Flags().GetString("password")
		email, err3 := cmd.Flags().GetString("email")
		if err1 != nil || err2 != nil || err3 != nil {
			return
		}
		if username == "" {
			fmt.Println("username is empty,input it")
			fmt.Print("username:")
			_, err := fmt.Scanln(&username)
			if err != nil {
				return
			}
		}
		if password == "" {
			fmt.Println("password is empty,input it")
			fmt.Print("password:")
			_, err := fmt.Scanln(&password)
			if err != nil {
				return
			}
		}
		if email == "" {
			fmt.Println("email is empty,input it")
			fmt.Print("email:")
			_, err := fmt.Scanln(&email)
			if err != nil {
				return
			}
		}

		cli, err := client.NewClientWithOpts(client.WithHost(host))
		if err != nil {
			fmt.Println(err)
			return
		}

		auth := types.AuthConfig{
			Password: password,
			Username: username,
			Email:    email,
		}
		res, err := cli.RegistryLogin(context.Background(), auth)
		if err != nil {
			fmt.Println(err)
			return
		}
		if res.Status != "Login Succeeded" {
			fmt.Println("Login Failed!")
			return
		}

		var config *util.PersistentConfig
		config, err = util.LoadPersistentConfigFromFile()
		if err != nil {
			config = &util.PersistentConfig{}
		}

		base := base64.URLEncoding.EncodeToString([]byte(util2.JsonEncode(auth)))
		config.Auth = base

		err = util.SavePersistentConfigFromFile(config)
		if err != nil {
			fmt.Println(err)
			return
		}

	},
}

func init() {
	rootCmd.AddCommand(loginCmd)
	loginCmd.Flags().StringP("username", "U", "", "repo user name")
	loginCmd.Flags().StringP("password", "W", "", "repo password")
	loginCmd.Flags().StringP("email", "E", "", "repo email")
	loginCmd.Flags().StringP("host", "H", "", "dockerd host")
}
